<template>
  <div style="border: 1px solid #ccc">
    <Toolbar
      style="border-bottom: 1px solid #ccc"
      :editor="editorRef"
      :defaultConfig="toolbarConfig"
      :mode="mode"
    />
    <Editor
      style="height: 300px"
      v-model="valueHtml"
      :defaultConfig="editorConfig"
      :mode="mode"
      @onCreated="handleCreated"
    />
  </div>
</template>

<script setup lang="ts">
import "@wangeditor/editor/dist/css/style.css"; // 引入 css

import {
  onBeforeUnmount,
  ref,
  shallowRef,
  onMounted,
  watch,
  reactive,
} from "vue";
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
import axios from "axios";
import { postAction } from "@/utils/system/commonUse";
import { ElMessage } from "element-plus";

// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef();

// 内容 HTML
const valueHtml = ref("");
watch(valueHtml, () => {
  console.log(valueHtml);
});

const mode = ref("default");

// 模拟 ajax 异步获取内容
onMounted(() => {
  // setTimeout(() => {
  //   valueHtml.value = "<p>模拟 Ajax 异步设置内容</p>";
  // }, 1500);
});

const toolbarConfig = {};
let editorConfig = {
  placeholder: "请输入内容...",
  MENU_CONF: {
    uploadImage: {},
  },
  // onChange(editor) {
  //   const html = editor.getHtml();
  //   console.log("editor content", html);
  //   // 也可以同步到 <textarea>
  // },
};
editorConfig.MENU_CONF["uploadImage"] = {
  // server: "http://192.168.5.175:8080/test/data",
  // form-data fieldName ，默认值 'wangeditor-uploaded-image'
  fieldName: "uploadFile",
  meta: {
    id: sessionStorage.getItem("id"),
    typeStr: "1002",
  },

  server: "http://47.96.231.238:8112/upload/uploadFile",
  // 8112/upload/uploadFile
};

defineExpose({
  valueHtml,
});

const obj = reactive({
  id: sessionStorage.getItem("id"),
  noticeTransfer: valueHtml,
  typeStr: "1",
});
// 服务器地址
const url = reactive({
  saveEditorUrl: "/project/saveOrUpdate",
});
const cliTest = () => {
  postAction(url.saveEditorUrl, obj)
    .then((data: any) => {
      console.log(data);

      if (data.code != 1000) {
        return ElMessage.error(data.msg);
      }
      console.log(data);
    })
    .catch((err) => {
      console.log(err);
    });
};

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value;
  if (editor == null) return;
  editor.destroy();
});

const handleCreated = (editor: any) => {
  console.log("editor", editor);

  editorRef.value = editor; // 记录 editor 实例，重要！
};
</script>

<style lang="scss" scoped></style>
